<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
  import echarts from 'echarts'
  require('echarts/theme/macarons')
  import { debounce } from '@/utils'

  export default {
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '350px'
      },
      dataList: {}
    },
    watch: {
      dataList(val) {
        this.list = val
        this.initChart()
      }
    },
    data() {
      return {
        chart: null
      }
    },
    mounted() {
      this.__resizeHanlder = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHanlder)
      this.initChart()
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHanlder)
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        const timeArray = []
        const dataArray = []
        for (var index in this.list) {
          const canTime = this.list[index].date.substr(5, 11).replace('-', '/')
          timeArray.push(canTime)
          dataArray.push(this.list[index].value)
        }
        this.chart = echarts.init(this.$el, 'macarons')
        this.chart.setOption({
          title: {
            text: '资源使用率',
            x: 10,
            y: 10
          },
          dataZoom: [{
            startValue: timeArray[0]
          }, {
            type: 'inside'
          }],
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            name: '时间',
            data: timeArray
          },
          yAxis: {
            name: '使用率',
            splitLine: {
              show: false
            }
          },
          grid: {
            x: '3.8%',
            y: '24.3%',
            x2: '5.5%',
            y2: '17%'
          },
          visualMap: {
            orient: 'horizontal',
            top: 40,
            right: 'right',
            min: 0,
            max: 1,
            splitNumber: 5,
            color: ['#d94e5d', '#eac736', '#50a3ba'],
            textStyle: {
              fontSize: 12,
              color: '#85B8D9'
            }
          },
          series: {
            name: '使用率',
            type: 'line',
            data: dataArray,
            markLine: {
              silent: true,
              data: [{
                yAxis: 0.2
              }, {
                yAxis: 0.4
              }, {
                yAxis: 0.6
              }, {
                yAxis: 0.8
              }]
            }
          }
        })
      }
    }
  }
</script>
